import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import {store} from '../store/index'
const asyncRouter: RouteRecordRaw[] = [...store.state.baseicRouters,...store.state.commitRouter]
// 将初始路由引入



// 权限路由过滤后添加到路由列表中
// asyncRouter 初期写入固定路由 但是需要将有需要的固定路由写在侧边栏
// routerArr.forEach((item) => {
//     asyncRouter.push(item) 
// })

// 创建路由
export const router = createRouter({
    history: createWebHashHistory(),
    routes: asyncRouter as unknown as RouteRecordRaw[],
    strict: true,
    scrollBehavior: () => ({ left: 0, top: 0 }),
})

// 重置路由
export function resetRouter() {
    router.getRoutes().forEach((route) => {
        // const { name } = route;
        // router.removeRoute(name)
    })
} 
// 路由首位--检测登录
router.beforeEach((to, _, next) => {  
    NProgress.start() // 进度条开始 
    //  在是使用了next()之后下面需要向下放行
    let token = sessionStorage.getItem('CREATE_ROUTER'); 
    let cat = sessionStorage.getItem('ROUTER_PATH') 
 
    if(!token){
        if(to.path=='/register'){
            next() 
        }else if(to.path!='/login'){
            next('/login') 
        } 
    }else if(token && to.path=='/login' || to.path=='/register'){ 
        next(cat as string)  
    } 
    next()
})
router.afterEach((to) => { 
    if(to.fullPath!=='/login'){
        // sessionStorage.setItem('ROUTER_PATH',to.fullPath) 
    } 
    NProgress.done() // 进度条结束
})
NProgress.configure({ ease: 'linear', speed: 500 })